package com.alm.handle.util;

import com.alm.handle.service.impl.SysDevCurrentDataServiceImpl;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.util.ReferenceCountUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class SendMessage {
    private static final Logger logger = LoggerFactory.getLogger(SysDevCurrentDataServiceImpl.class);
    public static boolean sendMessage(byte[] data, String devId) {
        devId=devId.toUpperCase();
        String ctxid=ContextManagerUtil.DEV_CHANNEL.get(devId);
        if(ctxid==null){
            logger.info("没有找到该记录");
            return false;
        }
        ChannelHandlerContext ctx = ContextManagerUtil.ctxMap.get(ctxid);
        if(ctx == null){
            //没有找到该记录
            logger.info("没有找到该记录");
            return false;
        }
        ByteBuf buf = Unpooled.unreleasableBuffer(Unpooled.copiedBuffer(data));
        try {
            if(ctx.channel().isWritable()){
                ctx.writeAndFlush(buf.duplicate());
                //发送成功
                logger.info("发送成功  发送的字节为："+getDataByString(data));
                return true;

            }
        }catch(Exception e){
            e.printStackTrace();
        }finally {
            ReferenceCountUtil.release(buf);
        }
        return false;
    }
    public static String getDataByString(byte[] bytes){
        StringBuffer str=new StringBuffer();
        for (int i=0;i<bytes.length;i++){
            str.append(String.format("%02x", bytes[i]));
        }
        return str.toString();
    }
}
